package com.hanson.common.handler;

import com.hanson.common.bean.ResultMessage;
import com.hanson.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    /**
     * 处理所有不可知异常
     *
     * @param e 异常
     * @return json结果
     */
    @ExceptionHandler(Exception.class)
    public ResultMessage handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultMessage.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作失败!，系统异常," + ExceptionUtils.getRootCauseMessage(e));
    }

    /**
     * 处理所有业务异常
     *
     * @param e 业务异常
     * @return json结果
     */
    @ExceptionHandler(BusinessException.class)
    public ResultMessage handleOpdRuntimeException(BusinessException e) {
        // 不打印异常堆栈信息
        log.error(e.getMsg());
        return ResultMessage.error(e.getCode(), e.getMessage());
    }
}
